<template>
  <!-- 采购建议 -->
  <div class="page-container">
    <page_breadcrumb :getKeyMethod="init_table_model" @change="change_table_model" pageOption />
    <ex_super_table_page v-bind="option" @selection-change="e => selection = e" ref="SuperTablePage">
    </ex_super_table_page>

    <!-- 修改建议采购数量 -->
    <ex_super_dialog_form ref="editQtyDialog" v-bind="editQtyOption" v-on="$listeners" @afterSubmitSuccess="reload">
    </ex_super_dialog_form>

    <!-- 生成采购订单 -->
    <suggestGenerateOrdeDialog ref="suggestGenerateOrdeRef" @submit="reload" />
  </div>
</template>

<script>
import suggestGenerateOrdeDialog from "../dialog/suggest_generate_orde_dialog";

import superTablePageFunction from "@/mixin/super-table-page-function";
import page_table_model_manage from "@/mixin/page_table_model_manage";
import emitOnFunction from "@/mixin/emit-on-function";
let emitKey = "oms>purchase>purchase_suggest";

export default {
  title: 'label_purchase_suggest',

  mixins: [
    superTablePageFunction,
    emitOnFunction(emitKey),
    page_table_model_manage,
  ],
  components: { suggestGenerateOrdeDialog },
  props: {
  },
  data() {
    return {
      batchEditQty: false,
      status: 'NORMAL_PURCHASE',
      option: {
        search: {
          default: { status: 'NORMAL_PURCHASE' },
          resetFieldFun: (def, org) => { def.status = org.status; return def },
          // formDataHandle: (data) => {
          //   return data
          // },
          model: [
            {
              key: 'status', label: 'label_status', itemClass: "w_fill",
              type: 'select',
              enum: 'PurchaseAuditStatusEnum',
              render: (h, { data }) => {
                const list = this.$enumOptions.PurchaseSuggestEnum
                  .map(it => (
                    <el-radio-button key={it} label={it}>
                      {this.$enumShow(it, 'PurchaseSuggestEnum')}
                    </el-radio-button>
                  ))
                return (<el-radio-group value={data.status}
                  onInput={e => {
                    this.$set(data, 'status', e)
                    this.status = e
                    this.$refs.SuperTablePage.loadDataForSearch()
                  }}>
                  {list}
                </el-radio-group>
                )
              }
            },
            { label: "label_customer", key: "customerId", type: 'common_customer_choose'},
            {
              label: "label_warehouse_name",
              key: "warehouseId",
              type: "base_warehouse_select",
            },
            { label: "label_sku", key: "skuId", type: "sku_selec_input" },

          ],
        },
        actionExtra: [
          {
            label: "label_purchase_generate_order",
            click: () => this.generateOrderFn(),
            if: () => this.status === 'NORMAL_PURCHASE',
            auth: 'oms_purchase_generate_order',
          },
          {
            label: "label_purchase_suspend_purchase",
            click: () => this.suspendPurchaseFn(),
            if: () => this.status === 'NORMAL_PURCHASE',
            auth: 'oms_purchase_suspend_purchase',
          },
          {
            label: "label_purchase_resume_purchase",
            click: () => this.resumePurchaseFn(),
            if: () => this.status === 'SUSPEND_PURCHASE',
            auth: 'oms_purchase_resume_purchase',
          },
          {
            label: "label_purchase_update_purchase_qty_batch",
            click: () => this.batchEditQtyFn(),
            if: () => this.status === 'NORMAL_PURCHASE',
            auth: 'oms_purchase_update_purchase_qty_batch',
          },
          {
            label: "label_export",
            click: this.exportExcel,
          },
        ],

        table: {
          url: "/oms-api/purchase/OmsPurchaseSuggestRpc/selectPage.json",
          model: this.init_table_model(),
        },
      },
      editQtyOption: {
        customClass: "dialog_auto",
        submitDataHandle: (data) => {
          // 批量修改
          if (this.batchEditQty) {
            const suggestList = this.selection.map(it => {
              return {
                id: it.id,
                suggestQty: data.suggestQty
              }
            })
            return { suggestList };
          } else {
            return { suggestList: [{ id: data.id, suggestQty: data.suggestQty }] };
          }
        },
        form: {
          itemClass: "form_item_default",
          inputClass: "form_input_default",
          model: [
            {
              key: "skuName",
              label: "label_sku_name",
              formatter: (r, c, v) => this.$formatNameCode(v, r.skuNameEn),
              formType: 'text',
              if: () => !this.batchEditQty
            },
            {
              key: "suggestQty",
              label: "label_purchase_suggest_count",
            }
          ],
          rules: {
            'suggestQty': [
              { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
            ]
          },
        }
      },
    }
  },
  methods: {
    option_table_model() {
      return [
        {
          type: "selection",
          clickToggle: true,
          keyGroup: "label_table_operate",
        },
        { key: 'skuName', "min-width": 130, label: 'label_sku_name', formatter: (r, c, v) => this.$formatNameCode(v, r.skuNameEn), 'show-overflow-tooltip': true, },
        {
          key: "skuCode",
          label: "label_sku_code",
          "min-width": 130,
          "show-overflow-tooltip": true,
        },

        {
          key: "warehouseName",
          label: "label_warehouse_name",
          "min-width": 130,
          "show-overflow-tooltip": true,
          formatter: (r, c, v) => this.$formatNameCode(v, r.warehouseCode),
        },
        {
          key: "supplierName",
          label: "label_supplier",
          "min-width": 130,
          "show-overflow-tooltip": true,
          formatter: (r, c, v) => this.$formatNameCode(v, r.supplierOnlyCode),
        },
        {
          key: "skuPrice",
          label: "label_unit_price",
          "min-width": 130,
          "show-overflow-tooltip": true,
        },
        { key: 'currencyCode', label: 'label_currency_kind', "min-width": 130, formatter: (r, c, v, i) => this.$enumShow(v, "CurrencyTypeEnum"), 'show-overflow-tooltip': true, },
        {
          key: "stockQty",
          label: "label_stock_count",
          "min-width": 130,
          "show-overflow-tooltip": true,
        },
        {
          key: "safeStockQty",
          label: "label_safety_stock_count",
          "min-width": 130,
          "show-overflow-tooltip": true,
        },
        {
          key: "suggestQty",
          label: "label_purchase_suggest_count",
          "min-width": 130,
          "show-overflow-tooltip": true,
          render: (h, { row, column }) => {
            if (this.status === 'NORMAL_PURCHASE') {
              return (
                <div class="clickClass" onClick={() => this.editQtyFn(row)}>
                  {row.suggestQty} <i class="el-icon-edit"></i>
                </div>
              );
            } else {
              return row.suggestQty
            }

          }
        },
        {
          key: "purchaser",
          label: "label_sku_buyer",
          "min-width": 130,
          "show-overflow-tooltip": true,
        },
        {
          key: "status",
          label: "label_status",
          width: 100,
          "show-overflow-tooltip": true,
          formatter: (r, c, v, i) =>
            this.$enumShow(v, "PurchaseSuggestEnum"),
        },
        {
          type: "operate",
          width: 150,
          operate: [
            {
              label: "label_purchase_generate_order",
              click: row => this.generateOrderFn(row),
              if: row => row.status === 'NORMAL_PURCHASE',
              auth: 'oms_purchase_generate_order'
            },
            {
              label: "label_purchase_suspend_purchase",
              type: "confirm-button",
              urlType: "json",
              url: '/oms-api/purchase/OmsPurchaseSuggestRpc/suspendPurchase.json',
              message: 'tip_purchase_suspend_purchase',
              if: row => row.status === 'NORMAL_PURCHASE',
              params: (v) => {
                return { idList: [v.id] }
              },
              done: ['reload', 'tip'],
              auth: 'oms_purchase_suspend_purchase',
            },
            {
              label: "label_purchase_resume_purchase",
              type: "confirm-button",
              urlType: "json",
              url: '/oms-api/purchase/OmsPurchaseSuggestRpc/resumePurchase.json',
              message: 'tip_purchase_resume_purchase',
              if: row => row.status === 'SUSPEND_PURCHASE',
              params: (v) => {
                return { idList: [v.id] }
              },
              done: ['reload', 'tip'],
              auth: 'oms_purchase_resume_purchase',
            },
          ],
        },
      ];
    },
    // 创建订单
    generateOrderFn(row) {
      let rows = this.selection
      if (row) {
        rows = [row]
      } else if (_.isEmpty(this.selection)) {
        return this.$message.error(this.$tt('tip_please_select_order'))
      }
      this.$refs.suggestGenerateOrdeRef.show(rows)
    },
    // 暂不采购
    suspendPurchaseFn(row) {
      let rows = this.selection
      if (row) {
        rows = [row]
      } else if (_.isEmpty(this.selection)) {
        return this.$message.error(this.$tt('tip_please_select_order'))
      }
      this.$ajax({
        url: '/oms-api/purchase/OmsPurchaseSuggestRpc/suspendPurchase.json',
        type: "json",
        data: { idList: rows.map(it => it.id) },
        success: (res) => {
          this.$message.success(this.$tt('tip_submit_success'))
          this.reload()
        },
      });
    },
    // 恢复采购
    resumePurchaseFn(row) {
      let rows = this.selection
      if (row) {
        rows = [row]
      } else if (_.isEmpty(this.selection)) {
        return this.$message.error(this.$tt('tip_please_select_order'))
      }
      this.$ajax({
        url: '/oms-api/purchase/OmsPurchaseSuggestRpc/resumePurchase.json',
        type: "json",
        data: { idList: rows.map(it => it.id) },
        success: (res) => {
          this.$message.success(this.$tt('tip_submit_success'))
          this.reload()
        },
      });
    },
    //修改采购数量
    editQtyFn(row) {
      this.batchEditQty = false
      this["$refs"]["editQtyDialog"].showNew({
        title: this.$t('label_purchase_update_purchase_qty'),
        submitUrl: '/oms-api/purchase/OmsPurchaseSuggestRpc/updatePurchaseQty.json',
        data: row
      });
    },
    batchEditQtyFn() {
      if (_.isEmpty(this.selection)) {
        return this.$message.error(this.$tt('tip_please_select_order'))
      }
      this.batchEditQty = true
      this.$refs['editQtyDialog'].showNew({
        title: this.$t('label_purchase_update_purchase_qty_batch'),
        submitUrl: '/oms-api/purchase/OmsPurchaseSuggestRpc/updatePurchaseQty.json'
      });
    },
    // 导出
    exportExcel() {
      const searchParams = this.$refs.SuperTablePage.getSearchData()
      let idList = []
      if (this.selection) {
        idList = this.selection.map(item => item.id)
      }
      let params = { ...searchParams, idList }
      this.$functionCommon({
        url: "/oms-api/purchase/OmsPurchaseSuggestRpc/exportExcel.json",
        data: params, type: 'form',
      })

    },
  }
};
</script>

<style lang="less" scoped>
/deep/.clickClass {
  cursor: pointer;
  color: #2EA7E0;
}
</style>
